package com.ciwong.epaper.modules.me.ui;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.application.EpaperConstant;
import com.ciwong.epaper.modules.me.adapter.ListViewAdapter;
import com.ciwong.epaper.modules.me.bean.Clazz;
import com.ciwong.epaper.modules.me.bean.Duiba;
import com.ciwong.epaper.modules.me.bean.MenuOptionBean;
import com.ciwong.epaper.modules.me.bean.SchoolDetail;
import com.ciwong.epaper.modules.me.bean.ServiceDetail;
import com.ciwong.epaper.modules.me.bean.UserBg;
import com.ciwong.epaper.modules.me.bean.UserInforDetailBean;
import com.ciwong.epaper.modules.me.dao.MeDao;
import com.ciwong.epaper.modules.me.util.MeJumpManager;
import com.ciwong.epaper.modules.pad.contentprovider.LoginToken;
import com.ciwong.epaper.modules.scan.util.ScanJumpManager;
import com.ciwong.epaper.ui.BaseFragment;
import com.ciwong.epaper.ui.MainActivity;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.BaseExtCallBack;
import com.ciwong.epaper.util.DateUtils;
import com.ciwong.epaper.util.DisplayUtils;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.util.FileUtil;
import com.ciwong.epaper.util.HttpRequest;
import com.ciwong.epaper.util.IntentFlag;
import com.ciwong.epaper.util.IntentValue;
import com.ciwong.epaper.util.RequestCode;
import com.ciwong.epaper.util.SerializableManager;
import com.ciwong.epaper.util.ViewUtil;
import com.ciwong.epaper.widget.DampScrollView;
import com.ciwong.epaper.widget.NewBottomMenuDialog;
import com.ciwong.epaper.widget.NewLoginDialog;
import com.ciwong.epaper.widget.NoScrollListView;
import com.ciwong.epaper.widget.titanic.FontSizeView;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.DeviceUtils;
import com.ciwong.libs.utils.FileUtils;
import com.ciwong.libs.utils.volley.BaseRequest;
import com.ciwong.mobilelib.application.BaseApplication;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.eyeguard.EyeGuardModeView;
import com.ciwong.mobilelib.eyeguard.permission.FloatWindowManager;
import com.ciwong.mobilelib.i.BaseCallBack;
import com.ciwong.mobilelib.i.OnItemClickListener;
import com.ciwong.mobilelib.i.ViewOnClickListener;
import com.ciwong.mobilelib.utils.BaseActivityManager;
import com.ciwong.mobilelib.utils.BaseJumpManager;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.utils.fileprovider.FileProvider7;
import com.ciwong.mobilelib.widget.BuyServiceDialog;
import com.ciwong.mobilelib.widget.CWDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.zxing.camera.CameraManager;

import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by RES-KUNZHU on 2015/7/24.
 */
public class MeFragment extends BaseFragment {

    /**
     * 跳转码，拍照
     */
    public static final int REQUEST_CODE_CAMERA = 0x0000011;
    /**
     * 跳转码，相册
     */
    public static final int REQUEST_CODE_ALBUM = 0x0000012;
    /**
     * 跳转码，拍照裁剪图片
     */
    public static final int REQUEST_CODE_CROP_CAMERA = 0x0000013;
    /**
     * 跳转码，相册裁剪图片
     */
    public static final int REQUEST_CODE_CROP_ALBUM = 0x0000014;
    /**
     * 去修改个人信息
     */
    public static final int REQUEST_CODE_TO_MODIFY_USER_INFO = 0x0000015;
    /**
     * 我的服务列表
     */
    public static final int REQUEST_CODE_TO_MY_SERVICES = 0x0000016;
    private final String TAG = "MeFragment";
    private Activity mActivity;
    private View view;
    private EApplication application;
    private UserInfoBase userInfo;
    private SchoolDetail schoolDetail;
    //测试视频讲解入口
    private List<SchoolDetail> mSchoolDetailList;
    public DampScrollView dampScrollView;
    private NoScrollListView listView;
    private ListViewAdapter adapter;
    private View content_view;
    private View me_title_bar_handle;
    private SimpleDraweeView img_user_avatar;
    private SimpleDraweeView img_personal_page_top;
    private TextView user_name_account;
    private TextView tx_service_status, tx_service_expiretime;
    private TextView tx_school_class;
    private TextView tv_point_rank;
    private RelativeLayout handle_top;
    private ViewGroup my_xunzhang_lay;
    private TextView my_jifen_tv, tx_flower_num;
    private ImageView qiandaoIm;
    private int[] pointRankImage = new int[]{R.mipmap.lv_green, R.mipmap.lv_blue, R.mipmap.lv_purple, R.mipmap.lv_yellow};
    private int width, height;
    private int overallXScroll = 0;
    private int bannerHeight = 250;// 滑动开始变色的高,真实项目中此高度是由广告轮播或其他首页view高度决定
    public static final String IS_USE_EYE_GUARD_MODE = "IS_USE_EYE_GUARD_MODE_";
    private CWDialog getSDcardPermissDialog;
    private final int CODE_REQUEST_WRITESD_PERMISSION = 8800;
    private ViewOnClickListener mViewOnClickListener = new ViewOnClickListener() {
        @Override
        public void avertRepeatOnClick(View v) {
            int id = v.getId();
            if (id == R.id.img_user_avatar || id == R.id.user_name_account) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(getActivity());
                    newLoginDialog.showLoginDialog();
                } else {
                    MeJumpManager.jumpToMyInfo(MeFragment.this, R.string.go_back, REQUEST_CODE_TO_MODIFY_USER_INFO);
                }

            } else if (id == R.id.my_xunzhang_lay) {
                //我的勋章页面
                BaseRequest.VerifyInfo verifyInfo = HttpRequest.getVerifyInfo();
                if (verifyInfo != null) {
                    String clientId = verifyInfo.getClientId();
                    String userId = EApplication.getInstance().getUserInfoBase().getUserId() + "";
                    String brandId = EApplication.BRAND_ID + "";
                    String startURL = EpaperConstant.URL_H5_MEDAL + "clientId=" + clientId + "&userId=" + userId + "&brandId=" + brandId;
                    MeJumpManager.jumpToDuiBaActivity(getActivity(), R.string.go_back, startURL);
                } else {
                    showToastError("无法获取用户信息，请重新登录后重试");
                }
            } else if (id == R.id.qiandaoIm) {
                //我的签到 到签到页面
                getDuibaLoginurl();

            } else if (id == R.id.btn_go_to_setting) {
                //跳转到设置界面
                MeJumpManager.jumpToSetting(mActivity, R.string.go_back, RequestCode.MainActivityResquestCode.REQUEST_CODE_TO_SETTING, MainActivity.JUMP_SORECE_TYPE_ME_SETTING);
            } else if (id == R.id.img_personal_page_top) {
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(getActivity());
                    newLoginDialog.showLoginDialog();

                } else {
                    bottomMenuDialog.show();
                }
            } else if (id == R.id.iv_setting_assess) {
                v.setSelected(!v.isSelected());
                CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_ASSESS + ((MainActivity) mActivity).getUserInfoBase().getUserId(), v.isSelected());

            } else if (id == R.id.iv_setting_listen_speak) {
                v.setSelected(!v.isSelected());
                CWSys.setSharedBoolean(EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO + ((MainActivity) mActivity).getUserInfoBase().getUserId(), v.isSelected());
            } else if (id == R.id.btn_micro_mall) {
                //拓展服务
                MeJumpManager.jumpToResourseCenterH5Activity(getActivity(), R.string.go_back, getResources().getString(R.string.resource_center));

            } else if (id == R.id.btn_mine_order) {
                if (application != null && application.isServiceExpired()) {
                    //学习中心
                    MeJumpManager.jumpToMineGrade(R.string.go_back, mActivity);
                } else {
                    setBuyServiceDialog();
                }

            } else if (id == R.id.btn_mine_grade) {
                //个人中心
                if (EConstants.IS_YOUKE) {
                    NewLoginDialog newLoginDialog = new NewLoginDialog(getActivity());
                    newLoginDialog.showLoginDialog();
                } else {
                    MeJumpManager.jumpToMyInfo(MeFragment.this, R.string.go_back, REQUEST_CODE_TO_MODIFY_USER_INFO);
                }
            } else if (id == R.id.btn_my_point) {
                MeJumpManager.jumpToMinePiontH5Activity(R.string.go_back, mActivity);
            }
        }
    };

    private BuyServiceDialog buyServiceDialog;

    public void setBuyServiceDialog() {
        if (buyServiceDialog == null) {
            buyServiceDialog = new BuyServiceDialog(mActivity);
            buyServiceDialog.setMenuOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    //拓展服务
                    MeJumpManager.jumpToResourseCenterH5Activity(mActivity, R.string.go_back, getResources().getString(R.string.resource_center));
                    buyServiceDialog.dismiss();
                }
            });
            buyServiceDialog.setClosOnClickListeners(new ViewOnClickListener() {
                @Override
                public void avertRepeatOnClick(View v) {
                    buyServiceDialog.dismiss();
                }
            });
        }
        buyServiceDialog.show();
    }

    private AdapterView.OnItemClickListener onItemClickListener = new OnItemClickListener() {
        @Override
        public void avertRepeatOnClick(AdapterView<?> adapterView, View view, int i, long l) {
            switch (i) {

                case 0:
                    //学习设置
                    showStudySettingDialog();
                    break;
                case 1:
                    showConfirmDialog(getActivity());
                    break;
                case 2:
                    //清除缓存
                    MeJumpManager.jumpToWipeCache(mActivity, R.string.go_back, EpaperConstant.REQUEST_CODE_WIPE_CACHE);
                    break;
                case 3:
                    //扫码
                    showgetCameraPermissDialog(1);
                    break;
                case 4:
                    //跳转到常见问题
                    MeJumpManager.jumpFAQActivity(R.string.go_back, mActivity, getString(R.string.faq_url), getString(R.string.faq));
                    break;
                case 5:
                    //跳到意见反馈
                    MeJumpManager.jumpToIssueRespActivity(R.string.go_back, getActivity());
                    break;
                case 6:
                    //跳转客服界面
                    MeJumpManager.jumpToKeFu(mActivity, R.string.go_back);
                    break;

            }
        }
    };

    /**
     * 使用照相机，判断权限
     */
    private void useSaoYiSaoCamera() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList_camera = new ArrayList<String>();
            Map<String, String> noteMap_camera = new HashMap<>();
            noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
            permissionList_camera.add(Manifest.permission.CAMERA);
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList_camera, //
                    noteMap_camera, //
                    CODE_REQUEST_SAOYISAO_CAMERA_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                ScanJumpManager.jumpCature(mActivity, CameraManager.CaptureMode.DEFAULT, IntentValue.ChooseServiceType.CHOOSE_SERVICE_TYPE_DEFAULT);
                            }
                        }
                    });
        } else {
            ScanJumpManager.jumpCature(mActivity, CameraManager.CaptureMode.DEFAULT, IntentValue.ChooseServiceType.CHOOSE_SERVICE_TYPE_DEFAULT);
        }
    }

    private Object userInfor;

    public MeFragment() {
        super();
    }

    private CWDialog cWDialog;

    private void showConfirmDialog(Context context) {
        if (context != null) {
            String msgTips = getString(R.string.dialog_hu_yan_tips);
            showConfirmDialog(context, msgTips);
        }

    }

    private void showConfirmDialog(Context context, CharSequence message) {
        if (cWDialog != null && cWDialog.isShowing()) {
            cWDialog.dismiss();
        }
        cWDialog = new CWDialog(context);
        cWDialog.setMessagWidePadding(message).setPositiveButton("关闭", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                cWDialog.dismiss();
            }
        }).show();

        cWDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                cWDialog.dismiss();
            }
        });
    }

    /**
     * 创建一个实例
     *
     * @return 返回一个实例
     */
    public static MeFragment newInstance() {
        MeFragment meFragment = new MeFragment();
        return meFragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_me, null);
        findView(view);
        init();
        return view;
    }

    private void findView(View view) {
        user_name_account = (TextView) view.findViewById(R.id.user_name_account);
        tx_service_status = (TextView) view.findViewById(R.id.tx_service_status);
        tx_service_expiretime = (TextView) view.findViewById(R.id.tx_service_expire_time);
        tx_school_class = (TextView) view.findViewById(R.id.tx_school_class);
        tv_point_rank = (TextView) view.findViewById(R.id.tv_point_rank);
        dampScrollView = (DampScrollView) view.findViewById(R.id.dampScrollView);
        listView = (NoScrollListView) view.findViewById(R.id.noscroll_listview);
        content_view = view.findViewById(R.id.content_view);
        dampScrollView.setbackGroundView(content_view);
        img_user_avatar = (SimpleDraweeView) view.findViewById(R.id.img_user_avatar);
        my_xunzhang_lay = view.findViewById(R.id.my_xunzhang_lay);
        qiandaoIm = view.findViewById(R.id.qiandaoIm);
        my_jifen_tv = view.findViewById(R.id.my_jifen_tv);
        tx_flower_num = view.findViewById(R.id.tx_flower_num);
        fsvSpeedControl = view.findViewById(R.id.fsv_speed_control);
        img_personal_page_top = (SimpleDraweeView) view.findViewById(R.id.img_personal_page_top);
        me_title_bar_handle = view.findViewById(R.id.me_title_bar_handle);
        me_title_bar_handle.bringToFront();
        dampScrollView.setOnScrollListener(new DampScrollView.OnScrollListener() {
            @Override
            public void onScroll(int scrollY) {
                overallXScroll = scrollY;// 累加y值 解决滑动一半y值为0
                if (overallXScroll <= 0) {   //设置标题的背景颜色
                    me_title_bar_handle.setBackgroundColor(Color.argb((int) 0, 0, 0, 0));
                } else if (overallXScroll > 0 && overallXScroll <= bannerHeight) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
                    float scale = (float) overallXScroll / bannerHeight;
                    float alpha = (float) (255 * scale * 0.2);
                    me_title_bar_handle.setBackgroundColor(Color.argb((int) alpha, 170, 178, 174));
                }
            }
        });

        listView.setFocusable(false);
        adapter = new ListViewAdapter(getActivity(), getDatas());
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(onItemClickListener);

        view.findViewById(R.id.btn_go_to_setting).setOnClickListener(mViewOnClickListener);
        view.findViewById(R.id.mine_order_bar).setOnClickListener(mViewOnClickListener);
        view.findViewById(R.id.btn_micro_mall).setOnClickListener(mViewOnClickListener);
        view.findViewById(R.id.btn_mine_order).setOnClickListener(mViewOnClickListener);
        view.findViewById(R.id.btn_mine_grade).setOnClickListener(mViewOnClickListener);
        user_name_account.setOnClickListener(mViewOnClickListener);
//		view.findViewById(R.id.btn_my_point).setOnClickListener(mViewOnClickListener);
        handle_top = (RelativeLayout) view.findViewById(R.id.handle_top);


        adapter.setOnEyeGuardOpenListener(new ListViewAdapter.OnEyeGuardOpenListener() {
            @Override
            public void isEyeGuardOpen(final ImageView imageView, final boolean isEyeGuardOpen) {
                final UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();

                if (!isEyeGuardOpen) {
                    //关闭护眼模式
                    if (userInfoBase != null) {
                        ESystem.setSharedBoolean(IS_USE_EYE_GUARD_MODE + userInfoBase.getUserId(), false);
                    }
                    imageView.setSelected(false);
                    BaseApplication.getInstance().isEyeGuardModeOpen = false;
                    BaseApplication.getInstance().isEyeGuardPerssionGet = false;
                    EyeGuardModeView.showEyeGuard(false);
                } else {
                    imageView.setSelected(false);
                    FloatWindowManager.getInstance().setOnFloatWindowPerssionGrantListener(new FloatWindowManager.OnFloatWindowPerssionGrantListener() {
                        @Override
                        public void onPerssionGranted() {
                            Log.e(TAG, "onPerssionGranted: ");
                            //只有获取到权限后，该标志才会置为true
                            if (userInfoBase != null) {
                                ESystem.setSharedBoolean(IS_USE_EYE_GUARD_MODE + userInfoBase.getUserId(), true);
                            }
                            BaseApplication.getInstance().isEyeGuardModeOpen = true;
                            BaseApplication.getInstance().isEyeGuardPerssionGet = true;
                            imageView.setSelected(true);
                            EyeGuardModeView.showEyeGuard(true);
                        }


                        @Override
                        public void onPerssionNoGranted() {
                            Log.e(TAG, "onPerssionNoGranted: ");
                            if (userInfoBase != null) {
                                ESystem.setSharedBoolean(IS_USE_EYE_GUARD_MODE + userInfoBase.getUserId(), false);
                            }
                            BaseApplication.getInstance().isEyeGuardModeOpen = false;
                            BaseApplication.getInstance().isEyeGuardPerssionGet = false;
                            imageView.setSelected(false);
                            EyeGuardModeView.showEyeGuard(false);
                        }

                        @Override
                        public void onGotoGetPerssion() {
                            BaseApplication.getInstance().isEyeGuardModeOpen = true;
                            imageView.setSelected(false);
                            Log.e(TAG, "onGotoGetPerssion: ");

                        }

                        @Override
                        public void onClickCheckSetMethod() {
                            BaseApplication.getInstance().isEyeGuardModeOpen = true;
                            imageView.setSelected(false);
                            MeJumpManager.jumpFAQActivity(R.string.go_back, mActivity, getString(R.string.faq_url), getString(R.string.faq));
                        }
                    }).applyOrShowFloatWindow(mActivity);
                }

            }
        });

    }

    public List<String> getDatas() {
        List<String> datas = new ArrayList<String>();
        datas.add("学习设置");
        datas.add("护眼模式");
        datas.add("清除缓存");
        datas.add("扫一扫");
        datas.add("常见问题");
        datas.add("投诉");
        datas.add("联系客服");
        return datas;
    }

    private void init() {
        tempFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels - DeviceUtils.dip2px(92);

        img_user_avatar.setOnClickListener(mViewOnClickListener);
        my_xunzhang_lay.setOnClickListener(mViewOnClickListener);
        qiandaoIm.setOnClickListener(mViewOnClickListener);
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) handle_top.getLayoutParams();
        params.width = width;
        params.height = width;
        handle_top.setLayoutParams(params);

        RelativeLayout.LayoutParams paramsImg = (RelativeLayout.LayoutParams) img_personal_page_top.getLayoutParams();
        paramsImg.width = width;
        paramsImg.height = width;

        img_personal_page_top.setLayoutParams(paramsImg);

        img_personal_page_top.setOnClickListener(mViewOnClickListener);
        application = (EApplication) mActivity.getApplication();
        setUserInfo();
        setBottomMenuDialog();
        ALiYunManager.getInstance().registerListener(listener);

        dampScrollView.setOnHeaderRefreshListener(new DampScrollView.OnHeaderRefreshListener() {
            @Override
            public void onHeaderRefresh() {
                Log.d(TAG, "######刷新个人信息#########");
                setMemberInfo(true);
            }
        });
        getSchoolByServer();
    }

    /**
     * //     * 设置用户信息
     * //
     */
    public void setUserInfo() {

        UserBg userBg = null;
        try {
            Log.d(TAG, "#######befor get userBg########");
            userBg = (UserBg) CWSys.getSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_USER_BG + SerializableManager.getInstance().getUserId(true));
            Log.d(TAG, "#######after userBg########");
            if (null != userBg) {
                Log.d(TAG, "#######null != userBg########" + userBg.getBackGround());
                Uri uri = Uri.parse(userBg.getBackGround());
                img_personal_page_top.setImageURI(uri);
            } else {
                Log.d(TAG, "#######null == userBg########");
                updateOrGetUserBg(null, true);
            }
            updateOrGetUserBg(null, true);
        } catch (IOException e) {
            e.printStackTrace();
            updateOrGetUserBg(null, true);
        } catch (Exception e) {
            e.printStackTrace();
            updateOrGetUserBg(null, true);
        }
        try {
            userInfo = application.getUserInfoBase();
            if (null != userInfo) {
                String avatar = userInfo.getAvatar();
                if (!TextUtils.isEmpty(avatar)) {
                    Uri uri = Uri.parse(avatar);
                    img_user_avatar.setImageURI(uri);
                } else {
                    ViewUtil.setLocalDefaultImg(img_user_avatar, R.mipmap.head);
                }
                user_name_account.setText(userInfo.getRealName() + "  " + userInfo.getUserId() + " ");
            }

            schoolDetail = application.getSchoolDetail();
            if (schoolDetail == null) {
                getSchoolByServer();
            } else {
                tx_school_class.setText(schoolDetail.getSchoolName());
                Clazz clazz = application.getClazz();
                if (clazz != null) {
                    tx_school_class.append("  " + clazz.getClassName());
                } else {
                    getAndSerializeClassList();
                }
            }
            setMemberInfo(false);

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        }

    }


    /**
     * 获取并缓存班级列表
     */
    private void getAndSerializeClassList() {
        MeDao.getInstance().getClassList(EApplication.BRAND_ID, new BaseCallBack() {
            @Override
            public void success(Object data) {
                final List<Clazz> clazzs = (List<Clazz>) data;
                Clazz clazz = application.getClazz();
                if (clazzs == null || clazzs.isEmpty()) {
                    clazz = null;
                } else {
                    int indexOf = clazzs.indexOf(clazz);
                    if (indexOf < 0) {
                        indexOf = 0;
                    }
                    clazz = clazzs.get(indexOf);
                }
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_DEFAULT, clazz);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CLASS_LIST, (Serializable) clazzs);

                application.setClazzs(clazzs);
                application.setClazz(clazz);

                if (null != schoolDetail) {
                    tx_school_class.setText(schoolDetail.getSchoolName());
                }
                if (clazz != null) {
                    tx_school_class.append("  " + clazz.getClassName());
                }
            }

            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d(TAG, "拉取班级列表失败:" + errorCode);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "拉取班级列表失败:" + data);
            }
        });
    }


    /**
     * 设置会员信息
     */
    public void setMemberInfo(boolean isFromServer) {
        List<ServiceDetail> mServiceDetails = application.getServiceDetails();
        //setServiceDetail(serviceDetail);
        //我的服务镇南关有购买未过期的显示VIP  无购买有试用显示试用 无购买无试用隐藏
        if (null != mServiceDetails && !isFromServer) {
            setMemberUiInfo(mServiceDetails);
        } else {
            UserInfoBase userInfoBase = application.getUserInfoBase();
            if (null != userInfoBase) {
                MeDao.getInstance().getServiceDetails(application, EApplication.BRAND_ID, userInfoBase.getUserId(), 0, new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {

                    @Override
                    public void failed(int errorCode, Object data) {
                        super.failed(errorCode, data);
                        //                                hideMiddleProgressBar();
                    }

                    @Override
                    public void failed(Object data) {
                        super.failed(data);
                        //                                hideMiddleProgressBar();
                    }

                    @Override
                    public void success(Object data) {
                        List<ServiceDetail> list = (List<ServiceDetail>) data;
                        SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_SERVICE_DETAIL_LIST, (Serializable) list);
                        application.setServiceDetails(list);
                        setMemberUiInfo(list);
                    }
                });
            }
        }

    }

    private void setMemberUiInfo(List<ServiceDetail> serviceDetails) {
        Log.d(TAG, "########刷新vip 信息#########");
        String isVip = "";
        String expireTime = "";
        if (serviceDetails != null) {
            for (ServiceDetail s : serviceDetails) {
                if (s.isVip()) {
                    isVip = "VIP";
                    expireTime = DateUtils.String2typeStr(s.getExpireTime(), DateUtils.DATE_LONG, DateUtils.DATE_SHORT0);
                    break;
                } else if (!s.isbExpired() && s.getSign() != 3 && !s.isBuy()) {//!s.isbExpired()&&s.getSign()!=3&&!s.isBuy()
                    isVip = "试用";
                    expireTime = DateUtils.String2typeStr(s.getExpireTime(), DateUtils.DATE_LONG, DateUtils.DATE_SHORT0);
                }
            }
        }

        if ("VIP".equals(isVip)) {
            tx_service_status.setVisibility(View.VISIBLE);
            tx_service_status.setText(R.string.me_vip);

            tx_service_expiretime.setText(" " + expireTime);
        } else if ("试用".equals(isVip)) {
            tx_service_status.setVisibility(View.VISIBLE);
            tx_service_status.setText(R.string.on_trial);
            tx_service_expiretime.setText(" " + expireTime);
        } else {
            tx_service_status.setVisibility(View.GONE);
            tx_service_expiretime.setVisibility(View.GONE);
        }
        tx_service_expiretime.setVisibility(View.GONE);
    }

    private void getSchoolByServer() {
        if (null == EApplication.getInstance().getUserInfoBase()) {
            Log.d(TAG, "#######null == EApplication.getInstance().getUserInfoBase()##########");
            return;
        }
        MeDao.getInstance().getSchoolInfo(new BaseExtCallBack(mActivity, EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void failed(Object data) {
                getSchoolByLocal();
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                getSchoolByLocal();
            }

            @Override
            public void success(Object data) {
                List<SchoolDetail> schoolDetails = (List<SchoolDetail>) data;
                if (schoolDetails.isEmpty()) {
                    schoolDetail = null;
                } else {
                    schoolDetail = schoolDetails.get(0);
                    try {
                        //刷新数据库的schoolId
                        if (EApplication.PLATFORM_ENV == EApplication.PLATFORM_PAD && schoolDetail != null) {
                            int schoolId = schoolDetail.getSchoolId();
                            LoginToken loginToken = LoginToken.queryTokenAndUserInfo(getActivity().getContentResolver());
                            if (null != loginToken) {
                                if (loginToken.getSchoolId() != schoolId) {
                                    loginToken.setSchoolId(schoolId);
                                    LoginToken.updateSchoolId(getActivity().getContentResolver(), loginToken);
                                }

                            }
                        }
                    } catch (Exception e) {

                    }

                }
                application.setSchoolDetail(schoolDetail);
                getAndSerializeClassList();
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_CHOOSE_SCHOOL, schoolDetail);
                SerializableManager.getInstance().serialize(SerializableManager.SerializeKey.SHARE_KEY_ALL_SCHOOL, (Serializable) schoolDetails);
            }
        });
    }

    private void getSchoolByLocal() {
        SerializableManager.getInstance().deSerialize(SerializableManager.SerializeKey.SHARE_KEY_ALL_SCHOOL, new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
            }

            @Override
            public void failed(Object data) {

            }

            @Override
            public void success(Object data) {
                mSchoolDetailList = (List<SchoolDetail>) data;
                if (!mSchoolDetailList.isEmpty()) {
                    schoolDetail = mSchoolDetailList.get(0);
                    application.setSchoolDetail(schoolDetail);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInforDetail();
    }

    public void getDuibaLoginurl() {
        try {
            MeDao.getInstance().getDuibaLoginurl(new BaseCallBack() {

                @Override
                public void success(Object data) {
                    super.success(data);
                    if (null != data) {
                        Duiba duiba = (Duiba) data;
                        String url = duiba.getDuiBaUrl();
                        if (url != null) {
                            MeJumpManager.jumpToDuiBaActivity(getActivity(), R.string.go_back, url);
                        }
                    }


                }

                @Override
                public void failed(int errorCode, Object data) {

                }

                @Override
                public void failed(Object data) {

                }
            }, application.getUserInfoBase().getUserId() + "");
        } catch (Exception e) {
            e.getStackTrace();
        }

    }


    public void getUserInforDetail() {
        MeDao.getInstance().getUserInforDetail(new BaseCallBack() {
            @Override
            public void failed(int errorCode, Object data) {
                CWLog.d(TAG, "data:" + data + errorCode);
            }

            @Override
            public void failed(Object data) {
                CWLog.d(TAG, "data:" + data);
            }

            @Override
            public void success(Object data) {
                super.success(data);
                if (data == null)
                    return;
                UserInforDetailBean userInforAndPointRankBean = (UserInforDetailBean) data;
                refrashPersonInfor(userInforAndPointRankBean);
                CWLog.d(TAG, "data:" + data);
            }
        });
    }

    //刷新个人信息
    private void refrashPersonInfor(UserInforDetailBean userInforAndPointRankBean) {
        if (!TextUtils.isEmpty(userInforAndPointRankBean.getAvatar())) {
            Uri uri = Uri.parse(userInforAndPointRankBean.getAvatar());
            img_user_avatar.setImageURI(uri);
        } else {
            ViewUtil.setLocalDefaultImg(img_user_avatar, R.mipmap.head);
        }
        setPointRankImage(userInforAndPointRankBean.getLevel());//设置等级
        user_name_account.setText(userInforAndPointRankBean.getRealName() + "  " + userInforAndPointRankBean.getUserId() + " ");
        my_jifen_tv.setText((int) userInforAndPointRankBean.getIntegral() + "");
        tx_flower_num.setText((int) userInforAndPointRankBean.getIntegral() + "");
    }

    private void setPointRankImage(int level) {
        if (level <= 0) {
            level = 1;
            tv_point_rank.setBackgroundResource(pointRankImage[0]);
        } else if (level <= 4) {
            tv_point_rank.setBackgroundResource(pointRankImage[0]);
        } else if (level <= 8) {
            tv_point_rank.setBackgroundResource(pointRankImage[1]);
        } else if (level <= 11) {
            tv_point_rank.setBackgroundResource(pointRankImage[2]);
        } else if (level >= 12) {
            tv_point_rank.setBackgroundResource(pointRankImage[3]);
        }
        tv_point_rank.setText("Lv." + level);
    }

    @Override
    public void onPause() {
        super.onPause();
//        StatService.onPause(getActivity());
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        this.mActivity = activity;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ALiYunManager.getInstance().unRegisterListener(listener);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            Uri outPuturi;
            switch (requestCode) {
                case REQUEST_CODE_CAMERA:
                    photoUri = FileProvider7.getUriForFile(getContext(), tempFile);
//                    if (Build.VERSION.SDK_INT >= 30) {
                    cutImgFile = FileUtil.uriToPicturesFileApiQ(photoUri, getContext());
//                    } else {
//                        cutImgFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
//                    }
//                    outPuturi = Uri.fromFile(cutImgFile);
//
//                    BaseJumpManager.jumpToSysCropPhoto(getActivity(), photoUri, outPuturi, REQUEST_CODE_CROP_CAMERA, true, 600, 600, true);
                    showGetPermissDialog();
                    break;
                case REQUEST_CODE_ALBUM:
                    if (data != null) {
                        photoUri = data.getData();
                        if (photoUri != null) {
//                            cutImgFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
//                            if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFile = FileUtil.uriToPicturesFileApiQ(photoUri, getActivity());
//                            } else {
//                                cutImgFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
//                            }
//
//                            outPuturi = Uri.fromFile(cutImgFile);
//                            BaseJumpManager.jumpToSysCropPhoto(getActivity(), photoUri, outPuturi, REQUEST_CODE_CROP_ALBUM, true, 600, 600, false);
                            showGetPermissDialog();
                        }
                    }
                    break;
                case REQUEST_CODE_CROP_ALBUM:
                case REQUEST_CODE_CROP_CAMERA:
                    if (null != cutImgFileTemp) {
                        if (Build.VERSION.SDK_INT >= 30) {
                            cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.getCropFile(getContext(), com.ciwong.mobilelib.utils.FileUtil.uri);
                        }
                        uploadAvatar(cutImgFileTemp.getPath());
                    }
                    break;
                case REQUEST_CODE_TO_MODIFY_USER_INFO:
                    if (data != null) {
                        int type = data.getIntExtra(IntentFlag.INTENT_FLAG_TYPE, -1);
                        switch (type) {
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_AVATAR:// 修改头像成功后回调
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_NAME:// 修改姓名成功后回调
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_SCHOOL:// 修改学校成功后回调
                            case IntentValue.ModifyUserInfoType.RESULT_MODIFY_CLASS:// 修改班级成功后回调
                                setUserInfo();
                                break;
                            default:
                                break;
                        }
                    }
                    break;
                case CODE_REQUEST_ALBUM_PERMISSION:
                    if (XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                        BaseJumpManager.jumpToSysAlbum(getActivity(), REQUEST_CODE_ALBUM);
                    }
                    break;
                case CODE_REQUEST_CAMERA_PERMISSION:
                    if (XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.CAMERA)) {
                        tempFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
                        BaseJumpManager.jumpToSysCamera(getActivity(), tempFile, REQUEST_CODE_CAMERA);
                    }
                    break;
                case CODE_REQUEST_SAOYISAO_CAMERA_PERMISSION:
                    if (XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.CAMERA)) {
                        ScanJumpManager.jumpCature(mActivity, CameraManager.CaptureMode.DEFAULT, IntentValue.ChooseServiceType.CHOOSE_SERVICE_TYPE_DEFAULT);
                    }
                    break;
            }
        }

    }

    private File tempFile;
    private File cutImgFile;
    private File cutImgFileTemp;
    private NewBottomMenuDialog bottomMenuDialog;

    private Uri photoUri;
    private final int CODE_REQUEST_ALBUM_PERMISSION = 9900;
    private final int CODE_REQUEST_CAMERA_PERMISSION = 9901;
    private final int CODE_REQUEST_SAOYISAO_CAMERA_PERMISSION = 9902;
    private AdapterView.OnItemClickListener bgOnItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch (position) {

                case 0:// 从相册选
                    showgetAlbumPermissDialog();
                    break;
                case 1:// 拍照
                    showgetCameraPermissDialog(0);
                    break;
                default:
                    break;
            }
            if (null != bottomMenuDialog && bottomMenuDialog.isShowing()) {
                bottomMenuDialog.dismiss();
            }
        }
    };

    private CWDialog getAlbumPermissDialog;

    /**
     * 获取Album权限提示框
     */
    private boolean showgetAlbumPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            useAlbum();
        } else {
            if (getAlbumPermissDialog == null) {
                getAlbumPermissDialog = new CWDialog(getActivity());
                getAlbumPermissDialog.setTitle(R.string.get_permiss_title);
                getAlbumPermissDialog.setTitleTextColor(Color.BLACK);
                getAlbumPermissDialog.setMessage(getString(R.string.get_album_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getAlbumPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                        useAlbum();
                    }
                });
                getAlbumPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getAlbumPermissDialog.dismiss();
                    }
                });
            }
            getAlbumPermissDialog.show();
        }
        return true;
    }

    private CWDialog getCameraPermissDialog;

    /**
     * 获取Camera权限提示框
     */
    private boolean showgetCameraPermissDialog(final int type) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.CAMERA);
        if (isHavePermiss) {
            if (type == 0) {
                useCamera();
            } else {
                useSaoYiSaoCamera();
            }
        } else {
            if (getCameraPermissDialog == null) {
                getCameraPermissDialog = new CWDialog(getActivity());
                getCameraPermissDialog.setTitle(R.string.get_permiss_title);
                getCameraPermissDialog.setTitleTextColor(Color.BLACK);
                getCameraPermissDialog.setMessage(getString(R.string.get_camera_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getCameraPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                        if (type == 0) {
                            useCamera();
                        } else {
                            useSaoYiSaoCamera();
                        }
                    }
                });
                getCameraPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getCameraPermissDialog.dismiss();
                    }
                });
            }
            getCameraPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用相册，判断权限
     */
    private void useAlbum() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_ALBUM_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                BaseJumpManager.jumpToSysAlbum(getActivity(), REQUEST_CODE_ALBUM);
                            }
                        }
                    });
        } else {
            BaseJumpManager.jumpToSysAlbum(getActivity(), REQUEST_CODE_ALBUM);
        }
    }

    /**
     * 使用照相机，判断权限
     */
    private void useCamera() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList_camera = new ArrayList<String>();
            Map<String, String> noteMap_camera = new HashMap<>();
            noteMap_camera.put(Manifest.permission.CAMERA, "相机权限");
            permissionList_camera.add(Manifest.permission.CAMERA);
//            if (Build.VERSION.SDK_INT >= 30) {
//                permissionList_camera.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
//                noteMap_camera.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, "读取相册权限");
//            }
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList_camera, //
                    noteMap_camera, //
                    CODE_REQUEST_CAMERA_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                tempFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
                                BaseJumpManager.jumpToSysCamera(getActivity(), tempFile, REQUEST_CODE_CAMERA);
                            }
                        }
                    });
        } else {
            tempFile = ESystem.getPicturesCacheDir(getActivity(), ViewUtil.getPhotoFileName());
            BaseJumpManager.jumpToSysCamera(getActivity(), tempFile, REQUEST_CODE_CAMERA);
        }
    }


    private void setBottomMenuDialog() {
        bottomMenuDialog = new NewBottomMenuDialog(getActivity());
        bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_photo, "从相册中选择"));
        bottomMenuDialog.addOption(new MenuOptionBean(R.mipmap.icon_caram, "拍照"));
        bottomMenuDialog.setOnItemClickListener(bgOnItemClickListener);
    }

    /**
     * 上传头像
     */
    private void uploadAvatar(final String localPath) {
        File file = new File(localPath);
        if (file.exists()) {
            showCricleProgress();
            ALiYunManager.getInstance().addFile(localPath, ALiYunManager.getInstance().getKey(localPath), localPath);
        } else {
            showToastError("文件不存在");
        }
    }

    private void updateOrGetUserBg(final String url, final boolean isGet) {
        if (EApplication.getInstance() == null || EApplication.getInstance().getUserInfoBase() == null || EApplication.getInstance().getUserInfoBase().getUserId() <= 0)
            return;
        MeDao.getInstance().updateUserBgInfo(url, isGet, new BaseExtCallBack(getActivity(), EApplication.getInstance().getUserInfoBase().getUserId() + "") {
            @Override
            public void success(Object data) {
                if (data != null) {
                    // 修改我的页面背景成功
                    UserBg userBg = (UserBg) data;
                    Uri uri = null;
                    if (isGet) {
                        uri = Uri.parse(((UserBg) data).getBackGround());
                    } else if (!TextUtils.isEmpty(url)) {
                        uri = Uri.parse(url);
                        showToastSuccess(R.string.modify_user_bg_success);

                    }
                    if (null != uri)
                        img_personal_page_top.setImageURI(uri);

                    if (null != userBg) {
                        try {
                            CWSys.setSharedSerializable(SerializableManager.SerializeKey.SHARE_KEY_USER_BG + SerializableManager.getInstance().getUserId(true), userBg);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                hideCricleProgress();
            }

            @Override
            public void failed(int errorCode, Object data) {
                super.failed(errorCode, data);
                hideCricleProgress();
                if (errorCode == 90002) {
                    showToastError(errorCode, data);
                } else if (!isGet) {
                    showToastError(R.string.modify_avatar_fail);
                }

            }

            @Override
            public void failed(Object data) {
                hideCricleProgress();
                /*if (!isGet) {
                    showToastError(R.string.modify_avatar_fail);
                }*/
            }
        });
    }


    private ALiYunManager.ALiYunListener listener = new ALiYunManager.ALiYunListener() {
        @Override
        public void onProgress(Object tag, long currentSize, long totalSize) {

        }

        @Override
        public void onSuccess(Object tag, String url) {
            if (null != cutImgFileTemp && cutImgFileTemp.getPath().equals(tag)) {
                FileUtils.delete(String.valueOf(tag));
                //            hideCricleProgress();
                updateOrGetUserBg(url, false);
            }
        }

        @Override
        public void onFailure(Object tag, int errorCode) {
            hideCricleProgress();

            if (null != cutImgFileTemp && cutImgFileTemp.getPath().equals(tag)) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToastError(R.string.upload_img_fail);
                    }
                });
            }
        }
    };


    private Dialog dialog;
    private View inflate;
    private ImageView ivAssess;
    private Button btnClose;
    private ImageView iv_setting_listen_speak;
    private FontSizeView fsvFontSize;
    private int defaultPos = 1;
    /**
     * 控制播放速度控件
     */
    private FontSizeView fsvSpeedControl;
    /**
     * 速度控件的档位
     */
    private int defaultSpeedPos = 1;

    public void showStudySettingDialog() {

        dialog = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        inflate = LayoutInflater.from(mActivity).inflate(R.layout.activity_read_setting, null); //初始化控件
        ivAssess = (ImageView) inflate.findViewById(R.id.iv_setting_assess);
        btnClose = (Button) inflate.findViewById(R.id.btn_close_setting);
        iv_setting_listen_speak = (ImageView) inflate.findViewById(R.id.iv_setting_listen_speak);
        fsvFontSize = (FontSizeView) inflate.findViewById(R.id.fsv_font_size);
        fsvSpeedControl = (FontSizeView) inflate.findViewById(R.id.fsv_speed_control);
        ivAssess.setOnClickListener(mViewOnClickListener);
        btnClose.setOnClickListener(mViewOnClickListener);
        iv_setting_listen_speak.setOnClickListener(mViewOnClickListener);

        //将布局设置给Dialog
        dialog.setContentView(inflate);
        boolean isAssess = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_ASSESS + ((MainActivity) mActivity).getUserInfoBase().getUserId(), false);

        ivAssess.setSelected(isAssess);
        boolean isPlayStemAudio = CWSys.getSharedBoolean(EConstants.SHARE_KEY_IS_PLAY_STEM_AUDIO + ((MainActivity) mActivity).getUserInfoBase().getUserId(), true);
        iv_setting_listen_speak.setSelected(isPlayStemAudio);
        //获取当前Activity所在的窗体
        Window dialogWindow = dialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
        lp.width = DisplayUtils.getScreenWidth(mActivity.getApplicationContext()); //设置宽度

        //设置字体滑动返回监听
        fsvFontSize.setChangeCallbackListener(new FontSizeView.OnChangeCallbackListener() {
            @Override
            public void onChangeListener(int position) {
                if (defaultPos == position) {
                    return;
                }
                defaultPos = position;
                //根据position 获取字体倍数
                EApplication.getInstance().mFontSizeScale = position;
                ESystem.setSharedInt("xixi:fontSizeScale", position);
                BaseActivityManager.getInstance().killAllActivity();
                MeJumpManager.jumpToMainActivity(mActivity, R.string.go_back,
                        EpaperConstant.REQUEST_CODE_LSW_JUMP_SETTING, MainActivity.JUMP_SORECE_TYPE_LSW);
                if (dialog != null) {
                    dialog.dismiss();
                }
            }
        });
        defaultPos = EApplication.getInstance().mFontSizeScale;
        //注意： 写在改变监听下面 —— 否则初始字体不会改变
        fsvFontSize.setDefaultPosition(defaultPos);

        //播放速度滑动返回监听
        fsvSpeedControl.setChangeCallbackListener(new FontSizeView.OnChangeCallbackListener() {
            @Override
            public void onChangeListener(int position) {
                if (defaultSpeedPos == position) {
                    return;
                }
                defaultSpeedPos = position;
                if (defaultSpeedPos == 0) {
                    //设置播放倍数为慢速
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        EApplication.getInstance().mPlayerspeed = 0.8f;
                        setSpeedBg(0.8f, true);
                    } else {
                        ToastUtil.INSTANCE.toastCenterError("当前Android系统版本过低，暂不支持调节语速");
                    }
                } else if (defaultSpeedPos == 1) {
                    //设置播放倍数为正常
                    EApplication.getInstance().mPlayerspeed = 1.0f;
                    setSpeedBg(1.0f, true);
                } else if (defaultSpeedPos == 2) {
                    //设置播放倍数为快速
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                        EApplication.getInstance().mPlayerspeed = 1.2f;
                        setSpeedBg(1.2f, true);
                    } else {
                        ToastUtil.INSTANCE.toastCenterError("当前Android系统版本过低，暂不支持调节语速");
                    }
                }
            }
        });
        float speed = EApplication.getInstance().mPlayerspeed;
        if (speed < 1.0f) {
            defaultSpeedPos = 0;
        } else if (speed > 1.0f) {
            defaultSpeedPos = 2;
        } else {
            defaultSpeedPos = 1;
        }
        //注意： 写在改变监听下面 —— 否则初始字体不会改变
        fsvSpeedControl.setDefaultPosition(defaultSpeedPos);
        dialog.getWindow().setAttributes(lp);
        dialog.show();//显示对话框
    }

    /**
     * 设置播放速度
     *
     * @param speed
     * @param isSet 读取or设置
     */
    private void setSpeedBg(float speed, boolean isSet) {
        if (isSet) {
            final UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
            ESystem.setSharedString("mPlayerspeed" + userInfoBase.getUserId(), String.valueOf(speed));
        } else {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                fsvSpeedControl.setEnabled(false);
            }
        }
    }


    private boolean showGetPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (isHavePermiss) {
            checkSDcardpermiss();
        } else {
            if (getSDcardPermissDialog == null) {
                getSDcardPermissDialog = new CWDialog(getActivity());
                getSDcardPermissDialog.setTitle(R.string.get_permiss_title);
                getSDcardPermissDialog.setTitleTextColor(Color.BLACK);
                getSDcardPermissDialog.setMessage(getString(R.string.get_sdcard_photo_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getSDcardPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                        checkSDcardpermiss();
                    }
                });
                getSDcardPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getSDcardPermissDialog.dismiss();
                    }
                });
            }
            getSDcardPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用sd卡，判断权限
     */
    private boolean checkSDcardpermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && getActivity().getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            noteMap.put(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.read_and_write_local_storage_permissions));
            XXPermissionTool.checkPermissions(getActivity(), //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_WRITESD_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                Uri outPuturi = Uri.fromFile(cutImgFile);
                                Uri imgUri = FileProvider7.getUriForFile(getContext(), cutImgFile);
                                if (Build.VERSION.SDK_INT >= 30) {
                                    cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getContext(), true);
                                    //设置裁剪的图片地址Uri
                                    outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
                                } else {
                                    cutImgFileTemp = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
                                }
                                BaseJumpManager.jumpToSysCropPhoto(getActivity(), imgUri, outPuturi, cutImgFileTemp,
                                        REQUEST_CODE_CROP_CAMERA, true, 200, 200);
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            Uri outPuturi = Uri.fromFile(cutImgFile);
            Uri imgUri = FileProvider7.getUriForFile(getContext(), cutImgFile);

            if (Build.VERSION.SDK_INT >= 30) {
                cutImgFileTemp = com.ciwong.mobilelib.utils.FileUtil.createImageFile(getContext(), true);
                //设置裁剪的图片地址Uri
                outPuturi = com.ciwong.mobilelib.utils.FileUtil.uri;
            } else {
                cutImgFileTemp = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), System.currentTimeMillis() + ".png");
            }
            BaseJumpManager.jumpToSysCropPhoto(getActivity(), imgUri, outPuturi, cutImgFileTemp,
                    REQUEST_CODE_CROP_CAMERA, true, 200, 200);
        }
        return true;
    }

}
